import numpy as np
import torch
# 与numpy蕾丝
# 从数据中来
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
# 从numpy中来
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
# 从tensor中来
x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")
# same as numpy :init randomly:
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
# tensor attribute:
tensor = torch.rand(3,4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")

# operations on tensors
# apiUrl:https://pytorch.org/docs/stable/torch.html
# move to GPU:
if torch.cuda.is_available():
    tensor = tensor.to("cuda")
# same as numpy api:
tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)

# jion tensor:
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)

# operations
# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)


# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)

# tenson 广播：
print(f"{tensor} \n")
tensor.add_(5)
print(tensor)

# tensor is similar to numpy narray